//
//  LGControllerViewController.m
//  ALS3.0
//
//  Created by guomianxiang on 17/3/17.
//  Copyright © 2017年 guomianxiang. All rights reserved.
//

#import "LGControllerViewController.h"
#import "ALSBarButton.h"

#import "LGSortTVC.h"
#import "LGShowControllerTableVC.h"
#import "LGShowDoorTableVC.h"

#import "ALSHeader.h"
#import "LGDCTableHead.h"

//#import "LGSegmentedControl.h"

#import "SVProgressHUD.h"

@interface LGControllerViewController ()<UIScrollViewDelegate,UIPopoverPresentationControllerDelegate,LGSortDelegate>
@property (weak, nonatomic) IBOutlet UIButton *AutoAddControllerBtn;
@property (weak, nonatomic) IBOutlet UIButton *AddControllerBtn;
@property (weak, nonatomic) IBOutlet UIScrollView *scrollerView;
@property (weak, nonatomic) IBOutlet UIView *showControllerView;
@property (weak, nonatomic) IBOutlet UIView *showDoorView;
@property (strong, nonatomic) IBOutlet UISegmentedControl *segment;
@property (assign, nonatomic) BOOL administrators;
@property (strong, nonatomic) NSArray *rightBarButtonItems;
@property (weak, nonatomic) LGShowDoorTableVC *showDoorTVC;
@end

@implementation LGControllerViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.definesPresentationContext = YES;

    [self setLiftItem];

    [self setNotification];
    //超级管理员验证
    self.administrators = NSUDIsAdministrators;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (DCMI.controllers.count == 0) {
        // 无数据
        [self presentationData:NO];
    }else {
        // 有数据
        [self presentationData:YES];
    }
}
/**
 show=yes 有数据，显示控制器与门信息，显示rightBarButton、segment
 show=no 无数据，显示添加控制器按钮，显示navigationItem.title，隐藏rightBarButton
 
 @param show 是否显示控制器信息
 */
- (void)presentationData:(BOOL)show {
    self.scrollerView.hidden = !show;
    
    self.AutoAddControllerBtn.hidden = show;
    self.AddControllerBtn.hidden = show;
    
    if (show) {
        [self setRightItemWithShowIndex:self.segment.selectedSegmentIndex];
        self.navigationItem.title = nil;
        self.navigationItem.titleView = self.segment;
    }else {
        self.navigationItem.rightBarButtonItem = nil;
        self.navigationItem.titleView = nil;
        self.navigationItem.title = @"门禁控制器";
    }
}

- (void)setLiftItem {
    UIButton *back = [ALSBarButton backButtonWithTitle:@"主页"];
    [back addTarget:self.navigationController action:@selector(popViewControllerAnimated:) forControlEvents:(UIControlEventTouchUpInside)];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:back];
}

- (void)setRightItemWithShowIndex:(NSInteger)index {
    
    if (index == 0) {
        self.navigationItem.rightBarButtonItems = @[self.rightBarButtonItems[1]];
    }else {
        self.navigationItem.rightBarButtonItems = self.rightBarButtonItems;
    }
    
}

- (void)viewWillLayoutSubviews {
    [super viewWillLayoutSubviews];

    self.scrollerView.contentSize = CGSizeMake(2 * kScreen_W, 0);
    self.scrollerView.scrollEnabled = NO;//!self.administrators;
    self.scrollerView.delegate = self;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

}

- (void)setNotification {
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(getNotification:) name:CMDeleteAllItemNotification object:nil];
}

- (void)getNotification:(NSNotification *)notification {
    if ([notification.name isEqualToString:CMDeleteAllItemNotification]) {
        [self presentationData:NO];
    }
}

- (void)administratorPresentation {
    [SVProgressHUD showInfoWithStatus:@"请联系管理员"];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
}

- (IBAction)sementClick:(UISegmentedControl *)sender {
    [self.scrollerView setContentOffset:CGPointMake(sender.selectedSegmentIndex * kScreen_W, 0) animated:YES];
    [self setRightItemWithShowIndex:sender.selectedSegmentIndex];
}

- (void)rightItemButtonClick {
    if (!self.administrators) {
        [self administratorPresentation];
        return;
    }
    __weak LGControllerViewController *weakSelf = self;
    UIAlertAction *add = [UIAlertAction actionWithTitle:@"手动添加控制器" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf addControllerBtnClick:nil];
    }];
    
    UIAlertAction *autoAdd = [UIAlertAction actionWithTitle:@"自动搜索控制器" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf autoAddControllerBtnClick:nil];
    }];
    
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [alert addAction:add];
    [alert addAction:autoAdd];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)sortClick {
    [self performSegueWithIdentifier:@"popover" sender:nil];
}
- (IBAction)addControllerBtnClick:(UIButton *)sender {
    
    if (!self.administrators) {
        [self administratorPresentation];
        return;
    }

    [self performSegueWithIdentifier:@"controllerVCToInfoTableVC" sender:nil];
}

- (IBAction)autoAddControllerBtnClick:(UIButton *)sender {
    
    if (!self.administrators) {
        [self administratorPresentation];
        return;
    }
    
    [self performSegueWithIdentifier:@"controllerVCToSearchVC" sender:nil];
}

#pragma mark - UIScrollViewDelegate
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    int index = scrollView.contentOffset.x / kScreen_W;
    
    [_segment setSelectedSegmentIndex:index];
}

- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
}

#pragma mark - UIAdaptivePresentationControllerDelegate

- (UIModalPresentationStyle)adaptivePresentationStyleForPresentationController:(UIPresentationController *)controller {
    // 取消屏幕的自适应
    return UIModalPresentationNone;
}
#pragma mark - LGSortDelegate
- (void)sortSelectIndex:(NSInteger)index {
    self.showDoorTVC.showDoorSortState = index;
}
#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:@"popover"]) {
        LGSortTVC *VC = segue.destinationViewController;
        VC.preferredContentSize = CGSizeMake(120, 88);
        VC.sortDelegate = self;
        
        UIPopoverPresentationController *popverC = VC.popoverPresentationController;
        UIBarButtonItem *sortItem = self.rightBarButtonItems[0];
        popverC.sourceView = sortItem.customView;
//        popverC.barButtonItem = sortItem;
        popverC.delegate = self;
        popverC.sourceRect = sortItem.customView.bounds;
    }
    if ([segue.identifier isEqualToString:@"showDoorInfoVC"]) {
        self.showDoorTVC = segue.destinationViewController;
        self.showDoorTVC.showDoorSortState = NSUDIntLGShowDoorState;
    }
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
#pragma mark - load 
- (NSArray *)rightBarButtonItems {
    if (_rightBarButtonItems.count == 0) {
        UIButton *right = [[UIButton alloc]init];
        //    right.imageEdgeInsets = UIEdgeInsetsMake(0, 0, 0, -16);
        [right setImage:[UIImage imageNamed:@"PLUS"] forState:(UIControlStateNormal)];
        [right setImage:[UIImage imageNamed:@"PLUS-in"] forState:(UIControlStateHighlighted)];
        //    right.backgroundColor = [UIColor yellowColor];
        
        [right sizeToFit];
        [right addTarget:self action:@selector(rightItemButtonClick) forControlEvents:(UIControlEventTouchUpInside)];
        UIBarButtonItem *addItem =  [[UIBarButtonItem alloc]initWithCustomView:right];
        
        
        UIButton *sortBtn = [[UIButton alloc]init];
//        sortBtn.backgroundColor = [UIColor yellowColor];
        [sortBtn setImage:[UIImage imageNamed:@"sort"] forState:(UIControlStateNormal)];
        [sortBtn setImage:[UIImage imageNamed:@"sort-in"] forState:(UIControlStateHighlighted)];
        [sortBtn sizeToFit];
        //    sortBtn.backgroundColor = [UIColor redColor];
        
        [sortBtn addTarget:self action:@selector(sortClick) forControlEvents:(UIControlEventTouchUpInside)];
        UIBarButtonItem *sortItem =  [[UIBarButtonItem alloc]initWithCustomView:sortBtn];

        _rightBarButtonItems = @[sortItem,addItem];
    }
    return _rightBarButtonItems;
}

@end
